package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /***
     * 营业额数据统计
     * @param begin
     * @param end
     * @return
     */
    @ApiOperation("营业额数据统计")
    public TurnoverReportVO reportStatistics(LocalDate begin, LocalDate end) {
        //获取到需要统计的日期
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        //获取每日营业额
        List<Double> sumList = new ArrayList<>();
        for (LocalDate date : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double sum = orderMapper.sumByMap(map);
            sum = sum == null ? 0.0 : sum;
            sumList.add(sum);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(localDateList,","))
                .turnoverList(StringUtils.join(sumList,","))
                .build();
    }

    /***
     * 用户数据统计
     * @param begin
     * @param end
     * @return
     */
    @ApiOperation("用户数据统计")
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取到需要统计的日期
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        //获取总共用户数量和每日新增用户数量
        List<Integer> totalList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end",endTime);
            //获得在当前日期前总用户数
            Integer total = userMapper.countByMap(map);
            totalList.add(total);
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(localDateList,","))
                .totalUserList(StringUtils.join(totalList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /***
     * 订单数据统计
     * @param begin
     * @param end
     * @return
     */
    @ApiOperation("订单数据统计")
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //获取日期
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        List<Integer> orderNumber = new ArrayList<>();
        List<Integer> validNumber = new ArrayList<>();
        //获取每日的订单数据
        for (LocalDate date : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer total = orderMapper.countByMap(map);
            orderNumber.add(total);
            map.put("status",Orders.COMPLETED);
            Integer valid = orderMapper.countByMap(map);
            validNumber.add(valid);
        }
        //计算订单总数
        Integer orderCount = orderNumber.stream().reduce(Integer::sum).get();
        //计算有效订单总数
        Integer validCount = validNumber.stream().reduce(Integer::sum).get();
        //计算完成率
        Double orderCompletionRate = 0.0;
        if (orderCount != 0){
            orderCompletionRate = validCount.doubleValue() / orderCount.doubleValue();
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(localDateList,","))
                .orderCountList(StringUtils.join(orderNumber,","))
                .validOrderCountList(StringUtils.join(validNumber,","))
                .validOrderCount(validCount)
                .totalOrderCount(orderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /***
     * 获取销量top10的菜品信息
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsList = orderMapper.getTop10Statistics(beginTime,endTime);

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(goodsList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),","))
                .numberList(StringUtils.join(goodsList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),","))
                .build();
    }

    /***
     * 营业额数据导出
     * @param response
     */
    public void export(HttpServletResponse response) {
        //获取近30天营业数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        //获取输入流，打开模板文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        try {
            //基于模板创建一个Excel对象
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取对应的表
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充第一行数据
            sheet.getRow(1).getCell(1).setCellValue(beginDate + "至" +endDate);
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            //填充第四行数据
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获取第五行
            row = sheet.getRow(4);
            //填充第五行数据
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充30日的数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //从第8行开始填充数据
                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(String.valueOf(date));
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
